#ifndef AUDIORECORDTHREAD_H
#define AUDIORECORDTHREAD_H
#include "FFThread.h"
#include <QObject>
#include <QString>
#include <QFile>
#include <QDebug>

extern "C" {
#include <libavcodec/avcodec.h>
#include <libavdevice/avdevice.h>
#include <libavfilter/avfilter.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libpostproc/postprocess.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
}

enum AudioRecordState {
    AudioRecording,
    AudioRecordEnd,
    AudioRecordFail,
};

// WAV文件头（44字节）
struct WAVHeader{
    // RIFF chunk的id
    uint8_t riffChunkId[4] = {'R', 'I', 'F', 'F'};
    // RIFF chunk的data大小，即文件总长度减去8字节
    uint32_t riffChunkDataSize;

    // "WAVE"
    uint8_t format[4] = {'W', 'A', 'V', 'E'};

    /* fmt chunk */
    // fmt chunk的id
    uint8_t fmtChunkId[4] = {'f', 'm', 't', ' '};
    // fmt chunk的data大小：存储PCM数据时，是16
    uint32_t fmtChunkDataSize = 16;
    // 音频编码，1表示PCM，3表示Floating Point
    uint16_t audioFormat = 1;
    // 声道数
    uint16_t numChannels;
    // 采样率
    uint32_t sampleRate;
    // 字节率 = sampleRate * blockAlign
    uint32_t byteRate;
    // 一个样本的字节数 = bitsPerSample * numChannels >> 3
    uint16_t blockAlign;
    // 位深度
    uint16_t bitsPerSample;

    /* data chunk */
    // data chunk的id
    uint8_t dataChunkId[4] = {'d', 'a', 't', 'a'};
    // data chunk的data大小：音频数据的总长度，即文件总长度减去文件头的长度(一般是44)
    uint32_t dataChunkDataSize;
};

class AudioRecordThread : public FFThread{
    Q_OBJECT

private:
    void run();

    int duration = 0;

    int encode(AVCodecContext *ctx, AVPacket *pkt, AVPacket *aacPkt, QFile &outFile);

public:

    ~AudioRecordThread();

signals:
    void recordState(AudioRecordState state);

    void recordDuration(int duration);

};

#endif // AUDIORECORDTHREAD_H
